import { Params } from '@/components/Table';
import dayjs from 'dayjs';
//去除前后空格
export const trim = (str: string) => {
  return str.trimStart().trimEnd();
};
//修改分页参数
export const transformParams = (data: any, sort: any) => {
  let obj: Params = { ...data, page: data.current, per_page: data.pageSize };
  Object.keys(data).forEach((key) => {
    if (typeof obj[key] === 'string') {
      obj[key] = trim(obj[key]);
      if (obj[key] === '') obj[key] = undefined;
    }
  });
  if (Object.keys(sort).length > 0) {
    obj.sort = Object.keys(sort)
      .filter((key) => sort[key] === 'descend' || sort[key] === 'ascend')
      .map((key) => (sort[key] === 'ascend' ? key : '-' + key))
      .join(',');
  }

  return obj;
};

export const getCurrentMonthInfo = () => {
  const today = new Date();

  const mm = String(today.getMonth() + 1).padStart(2, '0');
  const yyyy = today.getFullYear();

  return yyyy + '-' + mm;
};

export const transformCasTree = (data: any) => {
  return data.map((item: any) => {
    if (item.children) {
      return {
        ...item,
        children: transformCasTree(item.children),
        value: item.id,
        label: item.name,
      };
    }
    return { ...item, value: item.id, label: item.name };
  });
};

//返回菜单权限数组
export const AccessMenuList = (data: any, type: number[]) => {
  let obj: any = [];
  function getMenuAccess(menus: any[]) {
    menus.forEach((item: any) => {
      if (type.includes(item.type)) obj.push(item.authority);
      if (item.children) {
        getMenuAccess(item.children);
      }
    });
  }
  getMenuAccess(data);
  return obj;
};

//返回按钮权限数组
export const AccessButtonList = () => {
  let obj: any = [];
  return obj;
};

// 获取权限数组
export const getButtonPermissions = (): string[] => {
  return AccessButtonList();
};

// 获取当前菜单id
export const getMenuId = (path: string) => {
  const pathArr = path.split('/');
  const pathName = pathArr[pathArr.length - 1];
  if (localStorage.getItem('xcMenuMap')) {
    const menuMap = JSON.parse(localStorage.getItem('xcMenuMap')!);
    return menuMap[pathName];
  } else {
    const menus = JSON.parse(localStorage.getItem('adminPermissions')!);
    let menuMap: any = {};
    function getMenuMap(menus: any[]) {
      menus.forEach((item: any) => {
        if (item.children && item.children.length > 0) {
          getMenuMap(item.children);
        }
        if (item.type === 0 || item.type === 1) {
          menuMap[item.authority] = item.id;
        }
      });
    }
    getMenuMap(menus);
    localStorage.setItem('xcMenuMap', JSON.stringify(menuMap));
    return menuMap[pathName];
  }
};

export const transformDraTree = (data: any) => {
  return data.map((item: any) => {
    if (item.children) {
      return {
        ...item,
        children: transformDraTree(item.children),
        key: item.id,
        title: item.name,
      };
    }
    return { ...item, key: item.id, title: item.name };
  });
};

// 获取树状结构全部子节点id数组
export const getTreeChildIds = (data: any) => {
  let arr: number[] = [];
  data.forEach((item: any) => {
    if (item.children && item.children.length > 0) {
      arr = arr.concat(getTreeChildIds(item.children));
    } else {
      arr.push(item.id);
    }
  });
  return arr;
};

// 去除树状结构空的children
export const removeEmptyChildren = (data: any) => {
  return data.map((item: any) => {
    return {
      ...item,
      children:
        item.children && item.children.length > 0 ? removeEmptyChildren(item.children) : null,
    };
  });
};

//日期选择器，只能选择今日之后的日期
export const disabledDate = (current: any) => {
  // 获取当前日期
  const today = new Date();
  // 设置今天的年、月、日
  const year = today.getFullYear();
  const month = today.getMonth();
  const day = today.getDate();
  // 将当前日期与所选日期进行比较
  return current && current < new Date(year, month, day);
};

// 根据 id / ids 返回地区信息
export const getDistrictById = (id: number | number[]) => {
  const chxMergeDistrict = localStorage.getItem('chxMergeDistrict');
  if (chxMergeDistrict) {
    // 展开数组
    const expandArr = (arr: any[]) => {
      let newArr: any[] = [];
      arr.forEach((item: any) => {
        newArr.push(item);
        if (item.children) {
          newArr = newArr.concat(expandArr(item.children));
        }
      });
      return newArr;
    };
    const districtArr = expandArr(JSON.parse(chxMergeDistrict));
    if (typeof id === 'number') {
      const district = districtArr.find((item: any) => item.id === id);
      return district ? district.name : '-';
    } else {
      const districtNames: string[] = id.map((item: number) => {
        const district = districtArr.find((districtItem: any) => districtItem.id === item);
        return district ? district.name : '-';
      });
      return districtNames.join('/');
    }
  } else {
    return '-';
  }
};

/**
 * 移除字符串中的制表符
 * @param {*} str
 * @returns
 */
export function removeTabs(str = '') {
  if (typeof str !== 'string') {
    return str;
  }
  return str.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '');
}
/**
 * 联系方式中间四位 ****
 * @param {string} phone 手机号码
 */
export const formatPhone = (phone: string) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};
/**
 * @description 日期相关处理
 */
export const dateUtil = {
  /**
   * @description 获取当前时间
   * @param {string} format 时间格式
   * @returns {string}
   */
  getCurrentDate(format = 'YYYY-MM-DD'): string {
    return dayjs(new Date()).format(format);
  },
};

export function getPageQuery() {
  const urlSearchParams = new URLSearchParams(window.location.search);
  const params = Object.fromEntries(urlSearchParams.entries());
  return params;
}
